package com.itheima.reggie.controller;


import cn.hutool.core.util.RandomUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Random;

@RestController
@Slf4j
public class UserController {
    @Autowired
    private HttpSession httpSession;
    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private UserService userService;

    @PostMapping("/user/sendMsg")
    public ResultInfo sendMsg(@RequestBody Map<String, String> map) {
        //接收参数
        String phone = map.get("phone");

        //生成验证码
//        String code = RandomUtil.randomNumbers(6);
        String code = "123";
        log.info("生成的验证码是:{}", code);

        httpSession.setAttribute("SMS_" + phone, code);

        //发送验证码
        /*注释掉就不会发送出去，只是生成验证码，我们自己知道就可以做测试*/
//        smsTemplate.sendSms(phone,code);

        return ResultInfo.success(null);
    }

    @PostMapping("/user/login")
    public ResultInfo login(@RequestBody Map<String, String> map) {
        String phone = map.get("phone");
        String code = map.get("code");
        //校验code
        String codeFromSession = (String) httpSession.getAttribute("SMS_" + phone);
        if (!StringUtils.equals(code, codeFromSession)
                || StringUtils.isEmpty(code)
                || StringUtils.isEmpty(codeFromSession)) {
            return ResultInfo.error("验证码出错");
        }
        //验证码正确，从寻数据库是否有对应的phone
        User user = userService.findByPhone(phone);
        if (user != null) {
            //如果有执行登录
        } else {
            //如果没有执行注册
            //1、此时user是null所以要构建一个user对象
            user = new User();
            //2、给空的user对象添加电话号
            user.setPhone(phone);
            user.setStatus(1);
            userService.add(user);
        }
        //将user保存进session
        httpSession.setAttribute("SESSION_USER",user);
        return ResultInfo.success(user);
    }


    @PostMapping("/user/logout")
    public ResultInfo logout(){

//        httpSession.removeAttribute("SESSION_USER");
        httpSession.invalidate();
        return ResultInfo.success(null);
    }

}
